from smap.driver import SmapDriver
from smap.util import periodicSequentialCall
import calendar
from dateutil import tz
from datetime import datetime
import os
import xlrd
import sys

class newHoboXlsxDriver(SmapDriver):
	
	def setup(self, opts):
		folder = '/home/dheinzerling/BSG/bsg on 169.229.130.74/!Projects/HVAC/UFAD/NSA - 2012/Data/HOBO/Plenum/new xlsx/'
		self.ids = {}
		self.data = {}
		for filename in os.listdir(folder):
			self.f = xlrd.open_workbook(folder + filename)
			dataName = filename[:7]
			data = self.f.sheet_by_index(0)
			dates = data.col_values(1)[2:]
			times = data.col_values(2)[2:]
			temps = data.col_values(3)[2:]
			rhs = data.col_values(4)[2:]
			self.data[dataName] = [dates,times,temps,rhs]
			if len(self.data[dataName][0]) > 0:
				ts_temp = self.add_timeseries('/%s' % dataName + '_temp', 'F', data_type="double")
				self.ids[dataName + '_temp'] = ts_temp['uuid']
				ts_rh = self.add_timeseries('/%s' % dataName + '_rh', '%', data_type="double")
				self.ids[dataName + '_rh'] = ts_rh['uuid']
			else:
				del self.data[dataName]
		self.period = opts.get("Period", 1000000)

	def start(self):
		periodicSequentialCall(self.read).start(self.period)
	
	def read(self):
		time_zone = tz.gettz('America/New_York')
		for dataName in self.data:
			print dataName
			errorCount = 0
			for i in xrange(len(self.data[dataName][0])):
				try:
					dttime = self.data[dataName][0][i] + self.data[dataName][1][i] 
					point_date = datetime(*xlrd.xldate_as_tuple(dttime,self.f.datemode)[:6]).replace(tzinfo = time_zone)
					smaptime = calendar.timegm(point_date.utctimetuple())
				except:
					print "Unexpected error:", sys.exc_info()[0]
					print dttime
					print point_date
					break
				try:
					temp = self.data[dataName][2][i]
					self.add(self.ids[dataName + '_temp'], smaptime, float(temp))
					rh = self.data[dataName][3][i]
					self.add(self.ids[dataName + '_rh'], smaptime, float(rh))
						
				except ValueError:
					errorCount += 1
			print errorCount
